# -*-coding:utf-8 -*-
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
from rest_framework.authtoken.models import Token


class MixBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, token=None, **kwargs):
        user = super(MixBackend, self).authenticate(request, username, password, **kwargs)
        if user is None:
            if token:
                tk = Token.objects.filter(key=token).get()
                user = tk.user
        else:
            token, created = Token.objects.get_or_create(user=user)
        return user


class TokenAuthenticationBackend(object):
    def authenticate(self, token):
        try:
            tk = Token.objects.filter(key=token).get()
            return tk.user
        except:
            return None
